import 'dart:convert';
import '../../../utils/age_util.dart';

/// 用户实体模型
/// 
/// 核心业务对象，代表系统中的用户
/// 包含用户的完整信息和业务属性
class UserEntity {
  final int? userid;
  final String? userPhone;
  final String? userEmail;
  final int? userCode;
  final String? username;
  final String? userAvatarUrl;
  final Map<String, dynamic>? userData;
  final int? userAge;
  final String? userGender;
  final String? userSignature;
  final List<String>? userTags;
  final int? userLikes;
  final int? userFollowers;
  final int? userPoints;
  final List<String>? userHobbies;
  final String? userCity;
  final List<String>? userImgUrls;
  final String? userFrequentPlaces;
  final String? userBirthday;
  final int? userLevel;
  final String? status;
  final Map<String, dynamic>? extraData;
  final String? createdAt;
  final String? lastLogin;
  final String? updatedAt;

  UserEntity({
    this.userid,
    this.userPhone,
    this.userEmail,
    this.userCode,
    this.username,
    this.userAvatarUrl,
    this.userData,
    this.userAge,
    this.userGender,
    this.userSignature,
    this.userTags,
    this.userLikes,
    this.userFollowers,
    this.userPoints,
    this.userHobbies,
    this.userCity,
    this.userImgUrls,
    this.userFrequentPlaces,
    this.userBirthday,
    this.userLevel,
    this.status,
    this.extraData,
    this.createdAt,
    this.lastLogin,
    this.updatedAt,
  });

  factory UserEntity.fromJson(Map<String, dynamic> json) {
    return UserEntity(
      userid: json['userid'] as int?,
      userPhone: json['userPhone'] as String?,
      userEmail: json['userEmail'] as String?,
      userCode: json['userCode'] as int?,
      username: json['username'] as String?,
      userAvatarUrl: json['userAvatarUrl'] as String?,
      userData: _parseMapField(json['userData']),
      userAge: json['userAge'] as int?,
      userGender: json['userGender'] as String?,
      userSignature: json['userSignature'] as String?,
      userTags: _parseListField(json['userTags']),
      userLikes: json['userLikes'] as int?,
      userFollowers: json['userFollowers'] as int?,
      userPoints: json['userPoints'] as int?,
      userHobbies: _parseListField(json['userHobbies']),
      userCity: json['userCity'] as String?,
      userImgUrls: _parseListField(json['userImgUrls']),
      userFrequentPlaces: json['userFrequentPlaces'] as String?,
      userBirthday: json['userBirthday'] as String?,
      userLevel: json['userLevel'] as int?,
      status: json['status'] as String?,
      extraData: _parseMapField(json['extraData']),
      createdAt: json['created_at'] as String?,
      lastLogin: json['last_login'] as String?,
      updatedAt: json['updated_at'] as String?,
    );
  }

  /// 解析 Map 字段（支持直接的 Map 和 JSON 字符串）
  static Map<String, dynamic>? _parseMapField(dynamic value) {
    if (value == null) return null;
    if (value is Map<String, dynamic>) return value;
    if (value is String) {
      try {
        final decoded = jsonDecode(value);
        return decoded is Map<String, dynamic> ? decoded : null;
      } catch (e) {
        return null;
      }
    }
    return null;
  }

  /// 解析 List 字段（支持直接的 List 和 JSON 字符串）
  static List<String>? _parseListField(dynamic value) {
    if (value == null) return null;
    if (value is List) {
      return value.map((e) => e.toString()).toList();
    }
    if (value is String) {
      try {
        final decoded = jsonDecode(value);
        if (decoded is List) {
          return decoded.map((e) => e.toString()).toList();
        }
      } catch (e) {
        return null;
      }
    }
    return null;
  }

  Map<String, dynamic> toJson() => {
        'userid': userid,
        'userPhone': userPhone,
        'userEmail': userEmail,
        'userCode': userCode,
        'username': username,
        'userAvatarUrl': userAvatarUrl,
        'userData': userData,
        'userAge': userAge,
        'userGender': userGender,
        'userSignature': userSignature,
        'userTags': userTags,
        'userLikes': userLikes,
        'userFollowers': userFollowers,
        'userPoints': userPoints,
        'userHobbies': userHobbies,
        'userCity': userCity,
        'userImgUrls': userImgUrls,
        'userFrequentPlaces': userFrequentPlaces,
        'userBirthday': userBirthday,
        'userLevel': userLevel,
        'status': status,
        'extraData': extraData,
        'created_at': createdAt,
        'last_login': lastLogin,
        'updated_at': updatedAt,
      };

  // ==================== 便利Getter方法 ====================

  /// 获取性别文本
  String get sexText {
    switch (userGender) {
      case '男':
        return '男';
      case '女':
        return '女';
      default:
        return '未知';
    }
  }

  /// 获取状态文本
  String get statusText => status ?? '未知';

  /// 获取用户显示名称（优先使用昵称，然后用户名）
  String get displayName => username ?? '';

  /// 获取头像URL（兼容旧版本的avatarUrl getter）
  String get avatarUrl => userAvatarUrl ?? '';
  
  /// 🎯 根据生日动态计算年龄（委托给 AgeUtil）
  /// 
  /// 确保年龄数据的一致性和准确性
  /// - 从 userBirthday 动态计算，而不是使用固定的 userAge 字段
  /// - 生日变更时，年龄自动更新
  /// - 委托给 Utils 层的 AgeUtil 进行计算
  /// 
  /// 示例：
  /// ```dart
  /// final user = UserEntity(userBirthday: '1990-01-01');
  /// print(user.age);  // 34（根据当前日期计算）
  /// ```
  int get age => AgeUtil.calculateAge(userBirthday);

  /// 获取融云Token（从extraData中获取）
  String get rongcloudToken => extraData?['token']?.toString() ?? '';

  /// 获取融云用户ID（从extraData中获取）
  String get rongcloudUserId => extraData?['rongcloud_user_id']?.toString() ?? '';

  /// 获取实名认证状态（从extraData中获取）
  Map<String, dynamic>? get realNameAuth => extraData?['realNameAuth'] as Map<String, dynamic>?;

  /// 是否已实名认证
  bool get isRealNameVerified => realNameAuth?['verified'] == true;

  @override
  String toString() {
    return 'UserEntity(userid: $userid, username: $username, phone: $userPhone)';
  }
}

